package com.companion.lh.app

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.widget.Toast
import com.companion.lh.companion_app.R
import com.companion.model.Response
import com.companion.service.LoginService
import com.companion.service.retrofit
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_login.*
import java.util.regex.Pattern

class LoginActivity : AppCompatActivity() {

    private val loginService = retrofit.create(LoginService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        verifyCodeBtn.setOnClickListener {
            if (getVerifyCode()) {
                toVerifyCodePage()
            }
        }
    }

    private fun toVerifyCodePage() {
        var intent = Intent(this, PasswordActivity::class.java)
        var bundle = Bundle()
        bundle.putString("phone", phoneEdit.text.toString())
        startActivity(intent, bundle)
    }

    private fun getVerifyCode(): Boolean {
        return if (isValidPhone()) {
            val phone = phoneEdit.text.toString()
            loginService.getVerifyCode(phone).subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe { response: Response? ->
                        run {
                            if (response?.code == 1) {
                                Toast.makeText(this, R.string.info_send_verifycode_success, Toast.LENGTH_SHORT)
                            } else {
                                Toast.makeText(this, R.string.info_send_verifycode_failure, Toast.LENGTH_SHORT)
                            }
                        } }
            true
        } else {
            false
        }
    }

    private fun isValidPhone(): Boolean {
        val phone = phoneEdit.text.toString()
        val regEx = "^1[3|4|5|7|8][0-9]{9}\$"
        val pattern = Pattern.compile(regEx)
        val matcher = pattern.matcher(phone)
        return if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, R.string.error_invalid_phone, Toast.LENGTH_SHORT).show()
            false
        } else if (!matcher.matches()) {
            Toast.makeText(this, R.string.error_incorrect_phone, Toast.LENGTH_SHORT).show()
            false
        } else true
    }


//    override fun onCreateOptionsMenu(menu: Menu): Boolean {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        menuInflater.inflate(R.menu.menu_login, menu)
//        return true
//    }

}
